<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>游戏选单</title>
    <link rel="shotcut icon" href="/f/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="/f/bootstrap-4.4.1-dist/css/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="/f/bootstrap-vue.min.css" />
    <link rel="stylesheet" href="/f/shop.css?6">
    <script src="/f/jquery-3.4.1.min.js"></script>
    <script src="/f/bootstrap.bundle.min.js"></script>
    <script src="/f/vue.min.js"></script>
    <script src="/f/bootstrap-vue.min.js"></script>

    <!--script src="/f/mock.js"></script-->
    <script src="/v1/mock.js"></script>
</head>

<body>
<div id="app">
    <nav class="navbar navbar-expand-sm home-menu">
        <a class="navbar-brand" href="/v3.html">
            <img src="/f/logo.png" class="d-inline-block align-center" height="40px">
            <span style="color:white">欢迎选择游戏</span>
        </a>
        <span class="ml-auto">
          <a href="/account.html" class="account-link">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-person-circle " viewBox="0 0 16 16">
              <path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/>
              <path fill-rule="evenodd" d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z"/>
            </svg>
          </a>
        </span>
    </nav>

    <div class="main" v-show="page==1">
        <h4>第一步: 选择版本和硬盘</h4>
        <h5>主机系统版本</h5>
        <table class="table table-bordered">
            <tr>
                <td v-for="(s, index) in sysvTab" @click="setSysv(s)">
                    <input type="checkbox" :checked="s.added">{{ s.name }}</input>
                </td>
            </tr>
        </table>
        <p>
        <h5>硬盘大小</h5>
        <table class="table table-bordered">
            <tr v-for="(n,i) in Math.ceil(hddTab.length/3)">
                <td v-for="(h, i) in hddTab.slice(i*3, i*3+3)" @click="setHdd(h.cap, h.size)">
                    <input type="radio" :checked="size==h.size">{{ h.name }}</input>
                </td>
            </tr>
        </table>
        <p>
        <div class="text-center">
          <button class="btn btn-danger" @click="jmpPage(2)">下一步</button>
        </div>
    </div>

    <!-- 候选游戏弹窗 -->
    <b-modal id="dialog2" centered :title="detail.name" hide-footer>
      <div v-if="detail.photo">
        <img class="img-thumbnail rounded" loading="lazy" :src="detail.photo">
      </div>
      <p>
      <h5>适用版本</h5> 
      <ul class="list-group list-group-horizontal">
        <li v-for="(k, i) in gameSysv(detail.id)" class="list-group-item">{{ k|sysv }}</li>
      </ul>
      <p>
      <h5>游戏类型</h5> 
      <ul class="list-group list-group-horizontal">
        <li v-for="(k, i) in detail.genres" class="list-group-item">{{ k|genre2 }}</li>
      </ul>
      <p>
      <h5>发布日期</h5>
      <p>{{ detail.released_at|todate }}</p>
      <p>
      <div v-if="detail.tags!=''">
        <h5>标签</h5>
        <p>{{ detail.tags }}</p>
        <p>
      </div>
      <div>
        <h5>游戏简介</h5>
        <p class="border" style="padding:5px" v-html="detail.des"></p>
      </div>
      
    </b-modal>

    <!-- 候选游戏弹窗 -->
    <b-modal id="dialog1" centered :title="candi.name" hide-footer>
      <ul class="list-group" style="max-height: 400px;overflow-y: scroll;" v-for="(v, i) in gameVersions(candi.id)">
        <li class="list-group-item">
          <div style="background-color: #dddddd;padding:3px" class="clearfix">
            <input type="checkbox" :checked="isAnyPending(v.id)" class="float-left" @click="setAllCandiPkg(v.id)"></input>
            <div v-if="v.photo" class="float-left" style="margin-right: 5px;">
              <img v-if="v.des==''" class="" loading="lazy" :src="v.photo" width="50" max-height="30">
              <img v-else class="" loading="lazy" :src="v.photo" width="50" height="50">
            </div>
            <div class="float-left">
              <b>{{ v.name }}</b>
              <div v-if="v.des" v-html="v.des"></div>
            </div>
          </div>
          <div class="option" v-for="(p,i) in versionPkgs(v.id)" @click="togglePkg(p)">
            <input type="checkbox" :checked="p.pending" :disabled="!p.fit || p.disable">
              <span v-if="p.fit">{{ p.name }}</span>
              <span v-else style="color:red">{{ p.name }}</span>
            </input>
            <span>({{ p.size|unit }})</span>
          </div>
        </li>
      </ul>
      <div class="clearfix" style="margin-top:5px">
        <button class="btn btn-danger float-right" :disabled="candi.size<=0" @click="addGame(candi)">选入安装</button>
      </div>
    </b-modal>

    <div class="main" v-show="page==2">
        <h4>第二步: 选择要玩的游戏 (系统版本: {{ sysver }})</h4>
        <div>
            <input style="width:100%;margin-bottom: 3px;" type="text" v-model="keyword" placeholder="搜索游戏名称或拼音">

            <div class="clearfix">
              <ul class="list-group list-group-flush scrollable sticky-top float-left" style="max-height: 500px;overflow-y: scroll;">
                <li v-for="(k, i) in gentab" class="list-group-item" :class="{ active:genre==k.id }" @click="choseGenre(k.id)">{{ k.name }}
                  <span v-if="genreBadge(k.id)>0" class="badge badge-danger">{{ genreBadge(k.id) }}</span>
                </li>
              </ul>

              <ul class="list-group scrollable">
                <li class="list-group-item border-0 rounded-0" style="padding:0.5rem 0.5rem 0 0.5rem" v-for="(g, index) in games" v-if="searchFilter(g)">
                    <div class="card">
                        <div class="card-horizontal">
                            <div class="img-square-wrapper" @click="popupDetail(g)">
                                <img :id="gameImgId(g)" class="gamelogo" loading="lazy" :src="g.photo" :alt="g.name">
                            </div>
                            <div class="game-card card-body">
                                <h4 class="game-title card-title">{{ g.name }}</h4>
                                <div class="clearfix">
                                  <div class="card-text float-left" style="font-size: 12px">{{ g.size|unit }}</div>
                                  <button class="btn game-btn" style="color: #dc3545;position: absolute;right:10px;bottom:10px" v-if="!g.added" @click="popup(g)">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-plus-circle-fill" viewBox="0 0 16 16">
  <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.5 4.5a.5.5 0 0 0-1 0v3h-3a.5.5 0 0 0 0 1h3v3a.5.5 0 0 0 1 0v-3h3a.5.5 0 0 0 0-1h-3v-3z"/>
</svg>
                                  </button>
                                  <div style="position: absolute;right:10px;bottom:10px" v-else>
                                    <button class="btn btn-link" @click="popup(g)">修改</button>
                                    <button class="btn game-btn" style="color: #6c757d" @click="removeGame(g)">
                                      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-dash-circle-fill" viewBox="0 0 16 16">
  <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM4.5 7.5a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7z"/>
</svg>
                                    </button>
                                  </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </li>
              </ul>
            </div>
        </div>

        <footer class="footer-menu" id="footer-menu">
          <nav class="navbar navbar-expand navbar-light bg-light" style="padding:0">
            <div class="collapse navbar-collapse">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <a class="nav-link" href="#">购物车 <span class="sr-only">(current)</span></a>
                </li>
              </ul>
              <span class="navbar-text">
                <button class="btn btn-link" @click="clearAddedGames()">清空</button>
              </span>
            </div>
          </nav>
          <ul class="list-group list-group-flush" style="max-height: 400px;overflow-y: scroll;">
            <li class="list-group-item" v-for="(g,i) in addedGames">
              <button class="btn btn-link float-right" @click="removeGame(g)">X</button>
              <a href="#" class="float-left" style="margin-right: 10px" @click="popup(g)">{{ g.name }}</a>
              <span class="badge badge-primary badge-pill">容量: {{ g.size|unit }}</span>
            </li>
          </ul>
        </footer>

        <footer class="footer clearfix">
          <div v-if="isSafari" class="float-left" style="font-size:1.5px;font-weight:normal;visibility:hidden">{{ volume|unit }}</div>
          <div class="btn-group dropup float-left">
            <button class="btn btn-warning dropdown-toggle" id="dropup2" style="background-color:#fffbd5" @click="openFooterMenu()">
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" class="bi bi-cart" viewBox="0 0 16 16" style="padding-bottom: 3px;">
                <path d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
              </svg>
              <span class="badge badge-pill badge-danger">{{ selectCount }}</span>
            </button>
            <span class="badge badge-pill align-self-center">{{ volume|unit }} / {{ size|unit }}</span>
          </div>
          <div class="" style="position: absolute;right:5px;bottom:5px;">
            <button type="button" class="btn btn-secondary" @click="page=1">上一步</button>
            <button type="button" class="btn btn-danger" @click="submit()">下一步</button>
          </div>
        </footer>
    </div>

    <div class="main" v-show="page==3">
      <h4>第三步: 点击提交生成订单</h4>
      <h5>订单信息</h5>
      <!--div>订单编号: {{ orderNo }} <button class="btn-sm btn-danger" @click="copyto(orderNo)">复制</button></div-->
      <div>共{{ addedGames.length }}个游戏 共计: {{ volume|unit }}/{{ size|unit }}</div>
      <div class="tip">提交后把单号或截图发给您的购物平台客服，委托他们把游戏安装到选购的硬盘内就可以了！（代拷贝请查看本页面下面联系方式）
      </div>

      <hr>
      <h5>商家信息</h5>
      <div>店铺信息: 单机永伴</div>
      <div>店铺电话: 13027732793</div>
      <div>店铺地址: 河南省郑州市中原区秦岭路六合幸福门1期10号楼1402</div>

      <hr>
      <h5>订单明细</h5>
      <ul class="list-group scrollable">
        <li class="list-group-item" v-for="(g, index) in addedGames">
            <div class="card">
                <div class="card-horizontal">
                    <div class="img-square-wrapper">
                        <img class="" :src="g.photo" :alt="g.name" width="100" height="100">
                    </div>
                    <div class="card-body">
                        <h4 class="card-title">{{ g.name }}</h4>
                        <p class="card-text">容量: {{ g.size|unit }}</p>
                    </div>
                </div>
            </div>
        </li>
      </ul>
      
      <p>
      <footer class="footer clearfix">
        <div class="float-left" style="margin-left: 10px;font-size:12px;font-weight:normal">{{ volume|unit }} / {{ size|unit }}</div>
        <div class="float-right">
          <button type="button" class="btn btn-secondary" @click="page=2">上一步</button>
          <button type="button" class="btn btn-danger" @click="submit2()">提交</button>
        </div>
      </footer>
    </div>

</div>

<script>
// 判断集合是否有交集
function hasIntersection(a, b) {
  s = [...a].find(x=>b.has(x));
  return s != undefined;
}

var app = new Vue({
  el: '#app',
  data: {
    sysv: new Set, // 当前系统版本(集合)
    sysvTab: [], // 系统版本表
    hddTab: [], // 硬盘容量表
    size: 0, // 当前实际总容量
    cap: 0, // 当前卡片总容量
    gentab: [], // 游戏分类表
    genre: 0, // 当前分类
    games: [], // 游戏列表
    gameMap: {}, // {id: game}
    versions: [], // 游戏版本表
    versionMap: {},
    pkgs: [], // 游戏包表
    pkgMap: {}, // {pkg_id:pkg}
    mainMap: {}, // 每个版本的主包 {version_id:pkg}
    keyword: "", // 搜索关键词
    detail: {}, // 弹出游戏详情
    candi: {}, // 弹出框候选游戏
    orderNo: "", // 订单号
    page: 1 // 1主页面,2订单页面
  },
  filters: {
    unit: function(s) {
      if (s <= 0) {
        return s.toFixed(2) + "G";
      }
      if (s >= 1024) {
        s = s / 1024;
        s = s.toFixed(2) + 'T';
      } else if (s >= 1) {
        s = s.toFixed(2) + "G";
      } else if (s >= 0.0009765) {
        s = s * 1024
        s = s.toFixed(2) + 'M';
      } else {
        s = s * 1024 * 1024;
        s = s.toFixed(2) + 'K';
      }
      return s
    },
    sysv: function(id) {
      for (let v of SYSVTAB) {
        if (v.id == id) {
          return v.name;
        }
      }
      return "";
    },
    genre2: function(id) {
      for (let v of GENTAB) {
        if (v.id == id) {
          return v.name;
        }
      }
      return "";
    },
    todate: function(t) {
      var d = new Date(t*1000);
      return d.toLocaleDateString().replace(/\//g, "-");
    }
  },
  computed: {
    isSafari: function() {
      var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
      var is_safari = navigator.userAgent.indexOf("Safari") > -1;
      if (is_chrome) {
        return false;
      }
      return is_safari;
    },
    sysver: function() {
      var out = [];
      for (let s of this.sysvTab) {
        if (s.added) {
          out.push(s.name);
        }
      }
      if (out.length == 0) {
        return '所有';
      }
      return out.join(',')
    },
    balance: function() {
        return this.size - this.volume;
    },
    // 已选容量
    volume: function() {
        var n = 0;
        for (let it of this.games) {
            if (it.added) {
                n += it.size;
            }
        }
        return n;
    },
    // 已选游戏总数
    selectCount: function() {
      return this.games.filter(g => g.added).length
    },
    addedGames: function() {
      var out = [];
      for (let g of this.games) {
        if (g.added) {
          out.push(g);
        }
      }
      return out;
    },
    addedGameIds: function() {
      return this.games.filter(x=>x.added).map(x=>x.id);
    },
    addedPkgIds: function() {
      return this.pkgs.filter(x=>x.added).map(x=>x.id);
    }
  },
  created() {
    this.sysvTab = SYSVTAB;
    this.hddTab = HDDTAB;
    this.gentab = GENTAB;
    this.games = GAMETAB;
    for (let g of this.games) {
      g.genres = new Set(g.genres);
    }
    this.gameMap = {};
    for (let g of this.games) {
      this.gameMap[g.id] = g;
    }
    this.versions = VERTAB;
    this.versionMap = {};
    for (let v of this.versions) {
      this.versionMap[v.id] = v;
    }
    this.pkgs = PKGTAB;
    this.pkgMap = {};
    this.mainMap = {};
    for (let p of this.pkgs) {
      p.fit = true; // 符合当前系统版本
      p.disable = false; // 是否禁用
      this.pkgMap[p.id] = p;
      p.sysv = new Set(p.sysv); // init sysv
      g = this.gameMap[p.game_id];
      if (g != undefined) {
        g.size += p.size;
      }
      if (p.type == 1) {
        this.mainMap[p.version_id] = p;
      }
    }

    this.games.sort((x,y)=>y.released_at-x.released_at||y.id-x.id)
    this.loadCart();
  },
  methods: {
    minOfSet: function(s) {
      if (s.size == 0) {
        return 0;
      }
      return Math.min(...s);
    },
    gameImgId: function(g) {
      return "gameimg-" + g.id;
    },
    // 自动寻找绑定id
    // 1. patch是中文, bind_id=主包
    // 2. patch系统版本比主包小, 当用户选择低版本时再绑定
    // 3. patch是免登录时, 强绑定
    autobind: function() {
      var main = null; // 上一个主包
      var mainv = 0; // 主包最小系统版本
      var curv = this.minOfSet(this.sysv); // 当前选择最小版本
      var pkgs = [...this.pkgs];
      pkgs.sort((x,y)=>x.game_id-y.game_id || x.version_id-y.version_id || x.type-y.type);
      for (let p of pkgs) {
        p.bind_id = 0;
        if (p.type == 1) {
          main = p;
          mainv = this.minOfSet(main.sysv);
        }
        if (!main)
          continue;
        if (p.type!=1 && p.lang == 'cn') {
          p.bind_id = main.id;
        }
        if (p.type == 8) {
          var v = this.minOfSet(p.sysv);
          if (v>0 && mainv>0 && v<mainv && v<=curv) {
            p.bind_id = main.id;
          }
        }
        if (p.type == 9) {
          p.bind_id = main.id;
        }
      }
    },
    // 包符合当前系统版本
    fitsysv: function(p) {
      // 金手指全版本可用
      if (p.type == 5) {
        return true;
      }
      return this.sysv.size==0 || hasIntersection(p.sysv, this.sysv);
    },
    updateVersionFit: function(version_id) {
      let pkgs = this.versionPkgs(version_id);
      let main = null; // 主包
      let down = null; // 降级包
      for (let p of pkgs) {
        if (p.type == 1) {
          main = p;
        } else if (p.type == 8) {
          down = p;
        } else {
          continue;
        }
        p.fit = this.fitsysv(p);
      }
      // 1. 如果主包不能玩, 但是降级包能玩, 就标记主包,禁用升级包,和版本小于等于降级包版本的DLC和MOD
      // 如果主包能玩并且没有升级包, 并且降级包能玩, 就标记降级包
      // 金手指全版本能用
      if (main && !main.fit && down && down.fit) {
        main.fit = true;
        for (let p of pkgs) {
          if (p.type == 2) {
            p.fit = false;
          } else if (p.type == 3 || p.type == 4) {
            p.fit = p.ver <= down.ver;
          } else if (p.type > 4) {
            p.fit = this.fitsysv(p);
          }
        }
      }
      // 2. 如果主包不能玩, 并且没有降级包, 所有包都不能选
      // 3. 如果主包能玩, 标记所有包
      else if (main && main.fit) {
        for (let p of pkgs) {
            p.fit = this.fitsysv(p);
        }
      }
    },
    updateGameSize: function() {
      for (let g of this.games) {
        g.size = 0;
      }
      for (let p of this.pkgs) {
        p.fit = false;
      }
      for (let ver of this.versions) {
        this.updateVersionFit(ver.id);
      }

      for (let p of this.pkgs) {
        g = this.gameMap[p.game_id];
        if (g!=undefined && p.fit){
          g.size += p.size;
        }
      }
    },
    setSysv: function(s) {
      v = s.id;
      if (this.sysv.has(v)) {
          this.sysv.delete(v);
          s.added = false;
      } else {
          this.sysv.add(v);
          s.added = true;
      }
      this.updateGameSize();
      this.autobind();
    },
    setHdd: function(cap, size) {
        this.cap = cap;
        this.size = size;
    },
    choseGenre: function(kid) {
      if (this.genre == kid) {
        this.genre = 0;
        this.games.sort((x,y)=>y.released_at-x.released_at||y.id-x.id);
      } else {
        if (kid == -1) {
          this.games.sort((x,y)=>y.released_at-x.released_at||y.id-x.id)
        } else if (kid == -2) {
          this.games.sort((x,y)=>y.adds-x.adds)
        }
        this.genre = kid;
      }
    },
    searchFilter: function(g) {
      // if (g.size <= 0) {
      //   return false;
      // }
      if (this.genre > 0) {
        if (!g.genres.has(this.genre)) {
          return false;
        }
      } else if (this.genre == -3) {
        if (g.players != 2 && g.players != 12) {
          return false;
        }
      } else if (this.genre == -4) {
        if (g.players != 13 && g.players != 14) {
          return false;
        }
      } else if (this.genre == -5) {
        if (!g.vr)
          return false;
      }
      var kw = this.keyword.toLowerCase();
      if (kw != "") {
          // 输入单字母, 用首字母搜索
          if (kw.length == 1 && /[a-z]/.test(kw)) {
              return g.letter == kw || g.pinyin.startsWith(kw);
          }
          // 其他用饱含查找
          let en = g.en.toLowerCase();
          let aka = g.aka.toLowerCase();
          if (g.name.indexOf(kw)<0 && en.indexOf(kw)<0 &&  g.pinyin.indexOf(kw)<0 && aka.indexOf(kw)<0 && g.tags.indexOf(kw)) {
              return false
          }
      }
      return true;
    },
    jmpPage: function(p) {
      if (p == 2) {
        if (this.size <= 0) {
          alert("请您先选择硬盘, 否则无法安装游戏嗷~");
          return;
        }
      }
      this.page = p;
    },
    // 弹出候选窗口
    popupDetail: function(game) {
      this.detail = game;
      this.$bvModal.show('dialog2');
    },
    // 弹出候选窗口
    popup: function(game) {
      this.candi = game;
      let pkgs = this.gamePkgs(game.id);
      let versions = this.gameVersions(game.id);
      // 一个游戏有多个版本, 默认只选第一个版本的包
      let first_version = 0;
      if (versions.length > 0) 
        first_version = versions[0].id;
      if (this.candi.added) {
        for (let p of pkgs) {
          p.pending = p.added;
        }
      } else {
        for (let p of pkgs) {
          if (p.version_id == first_version) {
            p.pending = p.fit;
            // 初始禁用状态
            if (p.pending && p.bind_id!=0) {
              p.disable = true;
            }
          }
        }
      }
      this.$bvModal.show('dialog1');
    },
    // 选入安装
    addGame: function(game) {
      let size = 0;
      pkgs = this.gamePkgs(game.id);
      for (let p of pkgs) {
        if (p.pending) {
          size += p.size;
        }
      }
      size = parseFloat(size.toFixed(2));
      var volume = this.volume;
      if (game.added) {
        volume -= game.size;
      }
      if (volume + size > this.size) {
          alert(`亲，您选择的游戏容量已超标(${this.volume} + ${size} > ${this.size})，请根据硬盘容量进行选择哦！`);
          return
      }
      game.size = size;
      game.added = true;
      for (let p of pkgs) {
        p.added = p.pending;
      }
      this.$bvModal.hide('dialog1');
      this.saveCart();
      AddToCart($('#'+this.gameImgId(game)), $('#dropup2'));
    },
    removeGame: function(game) {
      game.added = false;
      pkgs = this.gamePkgs(game.id);
      game.size = 0;
      for (let p of pkgs) {
        game.size += p.size;
        p.pending = false;
        p.added = false;
      }
      this.saveCart();
    },
    // 缓存购物车游戏
    saveCart: function() {
      let d = {
        'sysv_ids': [...app.sysv],
        'cap': this.cap,
        'size': this.size,
        'games': this.games.filter(x=>x.added).map(x=>({'id':x.id, 'size':x.size})),
        'pkg_ids': this.addedPkgIds
      }
      s = JSON.stringify(d);
      localStorage.setItem('cart', s);
    },
    // 加载购物车游戏
    loadCart: function() {
      s = localStorage.getItem('cart');
      if (!s) {
        return;
      }
      let d = JSON.parse(s) || {};
      if (!d.games)
        d.games = [];
      if (d.games.length <= 0)
        return;
      if (!d.pkg_ids)
        d.pkg_ids = [];
      this.cap = d.cap || 0;
      this.size = d.size || 0;
      let svs = new Set(d.sysv_ids || []);
      for (let sv of this.sysvTab) {
        if (svs.has(sv.id)) {
          this.setSysv(sv);
        }
      }
      for (let o of d.games) {
        let g = this.gameMap[o.id];
        if (g) {
          g.added = true;
          g.size = o.size;
        }
      }
      for (let id of d.pkg_ids) {
        p = this.pkgMap[id];
        if (p) {
          p.added = true;
        }
      }
      this.page = 2;
    },
    clearCart: function() {
      localStorage.setItem('cart', '{}');
    },
    // 游戏下的所有包
    gamePkgs: function(game_id) {
      var out = [];
      for (let p of this.pkgs) {
        if (p.game_id == game_id) {
          out.push(p);
        }
      }
      return out;
    },
    gameSysv: function(game_id) {
      pkgs = this.gamePkgs(game_id);
      var s = new Set();
      for (let p of pkgs) {
        for (let v of p.sysv) {
          s.add(v);
        }
      }
      return Array.from(s).sort();
    },
    // 游戏下所有的版本
    gameVersions: function(game_id) {
      var out = [];
      for (let v of this.versions) {
        if (v.game_id == game_id) {
          out.push(v);
        }
      }
      return out;
    },
    // 版本下的所有包
    versionPkgs: function(version_id) {
      var out = [];
      for (let p of this.pkgs) {
        if (p.version_id == version_id) {
          out.push(p);
        }
      }
      return out;
    },
    // 全选版本所有包
    setAllCandiPkg: function(version_id) {
      let pkgs = this.versionPkgs(version_id);
      let checked = pkgs.find(x=>x.fit&&x.pending);
      for (let p of pkgs) {
        if (!p.fit) {
          continue;
        }
        p.pending = !checked;
        if (p.pending && p.bind_id != 0) {
          p.disable = true;
        }
      }
    },
    // 选择全部包
    allPkgDisabled: function(game) {
      return !this.pkgs.find(x=>x.fit && x.game_id==game.id);
    },
    isAnyPending: function(version_id) {
      pkgs = this.versionPkgs(version_id);
      return !!pkgs.find(x=>x.fit && x.pending)
    },
    // 选择包
    togglePkg: function(p) {
      if (!p.fit || p.disable) {
        return
      }
      p.pending = !p.pending;
      for (let k of this.pkgs) {
        if(k.bind_id == p.id) {
          k.pending = p.pending;
          k.disable = p.pending;
        }
      }
    },
    genreBadge: function(genre_id) {
      return this.games.filter(x=>x.added && x.genres.has(genre_id)).length;
    },
    // 复制到剪切板
    copyto: function(text) {
      copyToClip(text);
      alert("复制成功, 不要复制错哟!");
    },
    openFooterMenu: function() {
      let m = $('#footer-menu');
      if (m.hasClass('open')) {
        m.removeClass('open');
      } else {
        m.addClass('open');
      }
      return false;
    },
    clearAddedGames: function() {
      for (let g of this.addedGames) {
        this.removeGame(g);
      }
    },
    submit: function() {
      var pkg_ids = [];
      for (let p of this.pkgs){
        if(p.added) {
          pkg_ids.push(p.id);
        }
      }
      let formData = new FormData();
      sv = Array.from(this.sysv).join();
      formData.append('sysv', sv)
      formData.append('cap', this.size)
      formData.append('pkgs', JSON.stringify(pkg_ids))
      fetch("/v1/placeorder1", {
          method: 'POST',
          body: formData,
      }).then(function(rsp) {
          let data = rsp.json();
          return data;
      }).then(function(data) {
          if (data.ok) {
            app.orderNo = data.result;
          } else {
            alert(data.description);
            return;
          }
          app.page = 3;
      });
    },
    submit2: function() {
      var pkg_ids = [];
      for (let p of this.pkgs){
        if(p.added) {
          pkg_ids.push(p.id);
        }
      }
      let that = this;
      let formData = new FormData();
      sv = Array.from(this.sysv).join();
      formData.append('no', this.orderNo)
      formData.append('sysv', sv)
      formData.append('cap', this.size)
      formData.append('pkgs', JSON.stringify(pkg_ids))
      fetch("/v1/placeorder2", {
          method: 'POST',
          body: formData,
      }).then(function(rsp) {
          let data = rsp.json();
          return data;
      }).then(function(data) {
          if (data.ok) {
            app.orderNo = data.result;
          } else {
            alert(data.description);
            return;
          }
          that.clearCart();
          alert("提交成功");
          window.location.href = "/account.html";
          //app.page = 3;
      });
    }
  }
});

function copyToClip(content) {
    var aux = document.createElement("textarea"); 
    //aux.setAttribute("value", content); 
    aux.value = content;
    document.body.appendChild(aux); 
    aux.select();
    document.execCommand("copy"); 
    document.body.removeChild(aux);
}

// 点旁白隐藏弹窗
var footer_menu = document.getElementById('footer-menu');
var dropup2 = document.getElementById('dropup2');
var close_elem = document.getElementsByClassName('close');
document.addEventListener('click', function(event) {
  var vis = $(footer_menu).hasClass('open');
  if (vis) {
    var b = footer_menu.contains(event.target);
    var b2 = dropup2.contains(event.target);
    var b3 = document.getElementsByClassName('modal fade show').length > 0;
    if (!b && !b2 && !b3) {
      event.stopPropagation();
      $(footer_menu).removeClass('open');
    }
  }
},true);

// 统计搜索词
var lastkw = "";
setInterval(function(){
  if (app.keyword != "" && app.keyword != lastkw) {
    lastkw = app.keyword;
    console.log('tick', lastkw);
    let formData = new FormData();
    formData.append("k", app.keyword);
    fetch("/v1/log/keyword", {
        method: 'POST',
        body: formData,
    })
  }
}, 4000);

function AddToCart(fromEl, toEl, callback)
{
    var fromX = fromEl.offset().left
    var fromY = fromEl.offset().top - $(document).scrollTop()
    var toX = toEl.offset().left;
    var toY = toEl.offset().top - $(document).scrollTop()
    var img = document.createElement('img')
    img.src = fromEl.attr('src')
    img.style.width = fromEl.width() + 'px'
    img.style.height = fromEl.height() + 'px'
    img.style.position = 'fixed'
    img.style.zIndex = '1031'
    img.style.left = fromX + 'px'
    img.style.top = fromY + 'px'
    img.style.opacity = "0.9";
    img.style.borderRadius = "10px";
    document.getElementsByTagName('body')[0].appendChild(img)
    var fakeEl = $(img)
    fakeEl.animate({
        width: fromEl.width() * 0.5,
        height: fromEl.height() * 0.5,
        left: toX,
        top: toY
    }, 900, null, function ()
    {
        fakeEl.remove()
        if (callback)
        {
            callback()
        }
    })
}

</script>
</body>
</html>